<template>
  <div class="params-container">
    <!-- 分类参数有动态参数和静态属性区分 -->
    <!-- 动态参数就是一些可供客户在商品详情页进行选择 -->
    <!-- 静态属性就是一些商品的规格描述等等 -->

    <!-- 头部的面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 一个卡片区域 -->
    <el-card class="box-card">
      <!-- 提示用户选择区域 -->
      <el-alert title="注意:只允许为第三级分类设置相关参数!" type="warning" :closable="false" show-icon> </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类:</span>
          <el-cascader v-model="cateKeys" :options="cateList" :props="cascaderProp" @change="cateChange" clearable></el-cascader>
        </el-col>
      </el-row>
      <!-- tab区域 -->
      <el-tabs v-model="activeName" @tab-click="tabChange">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 按钮区域 -->
          <el-button type="primary" size="mini" :disabled="isBtnsDisable" @click="addDialogVisible = true">添加参数</el-button>
          <el-table :data="manyTable" stripe border v-if="manyTable.length !== 0">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag -->
                <el-tag v-for="(item, index) in scope.row.attr_vals" :key="index" closable @close="removeTag(index, scope.row)">{{ item }}</el-tag>
                <!-- 输入框和button的切换 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"> </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号" width="100px"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="small" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="small" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isBtnsDisable" @click="addDialogVisible = true">添加属性</el-button>
          <el-table :data="onlyTable" stripe border v-if="onlyTable.length !== 0">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag -->
                <el-tag v-for="(item, index) in scope.row.attr_vals" :key="index" closable @close="removeTag(index, scope.row)">{{ item }}</el-tag>
                <!-- 输入框和button的切换 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"> </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号" width="100px"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="small" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="small" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 公用添加对话框 -->
    <el-dialog :title="'添加' + titleText" :visible.sync="addDialogVisible" width="40%" @close="resetAddForm">
      <!-- 表单部分 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 公用修改对话框 -->
    <el-dialog :title="'修改' + titleText" :visible.sync="editDialogVisible" width="40%" @close="closeEditDialog">
      <!-- 表单部分 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item label="活动名称" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getCateList()
  },
  data() {
    return {
      cateList: [],
      // 用来存储选中的父级商品分类的id
      cateKeys: [],
      // 级联选择器的配置对象
      cascaderProp: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover'
      },
      // tab组件绑定数据
      activeName: 'many',
      // 存储动态参数列表
      manyTable: [],
      // 存储静态参数列表
      onlyTable: [],
      // 控制添加对话框的显示与隐藏
      addDialogVisible: false,
      // 表单
      addForm: {
        attr_name: ''
      },
      // 表单的验证规则
      addFormRules: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      },
      /** **** 修改弹出对话框 ******/
      editDialogVisible: false,
      editForm: {},
      editFormRules: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      },

      /** **** 修改弹出对话框 ******/
      // 控制输入框和按钮显示与隐藏
      inputVisible: false,
      inputValue: ''
    }
  },
  methods: {
    // 获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品分类列表失败!')
      this.cateList = res.data
    },
    // 级联控件选择的内容发生变化时会触发，选中的value都会记录在parentCateKeys数组中
    cateChange() {
      this.getParamsData()
    },
    // Tabs组件切换响应事件
    tabChange() {
      this.getParamsData()
    },
    // 获取参数列表数据
    async getParamsData() {
      if (this.cateKeys.length !== 3) {
        // 选择的不是三级分类,重置cateKeys,不向服务器请求数据并return
        this.cateKeys = []
        this.manyTable = []
        this.onlyTable = []
        return
      }
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: this.activeName }
      })
      if (res.meta.status !== 200) return this.$message.error('获取参数列表失败,请检查是否选择的是三级分类!')
      // 遍历数组,将每个对象里的attr_vals字段里的内容转换为数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 为每一项item都添加新的属性
        item.inputVisible = false
        item.inputValue = ''
      })
      // 判断当前tab是动态参数还是静态属性
      if (this.activeName === 'many') {
        this.manyTable = res.data
      } else {
        this.onlyTable = res.data
      }
      console.log(res.data)
      console.log(this.cateKeys)
    },
    // 监听添加对话框的关闭事件
    resetAddForm() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加动态参数或静态属性
    addParams() {
      // 对表单进行预验证
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('添加失败!')
        this.$message.success('添加成功!')
        this.getParamsData()
        this.addDialogVisible = false
      })
    },
    /* 修改对话框start */
    editParams() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error('更新失败!')
        this.getParamsData()
        this.$message.success('更新成功')
        this.editDialogVisible = false
      })
    },
    async showEditDialog(attrId) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attrId}}`, {
        attr_sel: this.activeName
      })
      if (res.meta.status !== 200) return this.$message.error('获取失败!')
      console.log(res.data)
      this.editForm = res.data
      this.editDialogVisible = true
    },
    closeEditDialog() {
      this.$refs.editFormRef.resetFields()
    },
    removeParams(attrId) {
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async confirm => {
          const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${attrId}`)
          if (res.meta.status !== 200) return this.$message.error('删除失败!')
          this.getParamsData()
          this.editDialogVisible = false
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(err => err)
    },
    /* 修改对话框end */
    // enter按键和失去焦点触发事件
    async handleInputConfirm(row) {
      console.log(row, '11111')
      // 如果添加的tag里面的内容为0
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 将新的inputValue进行追加 让tag进行重新循环渲染
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.updateAttrVals(row)
    },
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async updateAttrVals(row) {
      // 向服务器发起请求
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_sel: this.activeName,
        attr_name: row.attr_name,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.$message.success('更新成功!')
    },
    removeTag(index, row) {
      // 删除下标为index的tag
      row.attr_vals.splice(index, 1)
      this.updateAttrVals(row)
    }
  },
  computed: {
    // 控制按钮是否可用
    isBtnsDisable() {
      // 如果级联选择器选中的不是三级分类,则禁用按钮
      if (this.cateKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    // 获取用户选取的三级分类的id
    cateId() {
      return this.cateKeys[2]
    },
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px;
}

.el-cascader {
  margin-left: 5px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
